//
//  GMTrainViewController.m
//  Teecloud
//
//  Created by 小熊 on 2018/6/27.
//  Copyright © 2018年 小熊. All rights reserved.
//

#import "GMTrainViewController.h"
#import "GMTrainViewCell.h"
#import "XZTrainRecord.h"
#import "XZSearchBar.h"
@interface GMTrainViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) XZSearchBar *searchBar;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *dataSource;
//搜索关键字
@property (nonatomic, copy) NSString *key;
@end

@implementation GMTrainViewController
#pragma mark - LifeCycle
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"培训记录";
    self.view.backgroundColor = kWhiteColor;
    [self creatTitleView];
    [self pullNewsData];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    self.key = self.searchBar.text;
     [self pullNewsData];
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
     [searchBar resignFirstResponder];
}

- (void)creatTitleView{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    //设置titleview，不过这个view并不是我们需要的居中的view；
    self.navigationItem.titleView = titleView;
    __weak typeof(self) weakSelf = self;
    //主线程列队一个block， 这样做 可以获取到autolayout布局后的frame，也就是titleview的frame。在viewDidLayoutSubviews中同样可以获取到布局后的坐标
    __block XZSearchBar *searchBar;
    dispatch_async(dispatch_get_main_queue(), ^{
        //要居中view的宽度
        CGFloat width = 240;
        //实际居中的view
        UIView *centerView = [[UIView alloc]init];
        centerView.backgroundColor = kClearColor;
        //设置一个基于window居中的坐标
        centerView.frame = CGRectMake((DEVICE_WIDTH-width)/2, 20+(kIs_iPhoneX?24:0), width, 44);
        //坐标系转换到titleview
        centerView.frame = [weakSelf.view.window convertRect:centerView.frame toView:weakSelf.navigationItem.titleView];
        searchBar = [[XZSearchBar alloc]initWithFrame:CGRectMake(0, 10, 240, 30)];
        searchBar.delegate = self;
        searchBar.placeholder = @"输入关键字";
        searchBar.tintColor = kBlueColor;
        [centerView addSubview:searchBar];
        self.searchBar = searchBar;
        //centerview添加到titleview
        [weakSelf.navigationItem.titleView addSubview:centerView];
    });
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     self.tableView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GMTrainViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //解决xib复用数据混乱问题
    if (nil == cell) {
        cell= (GMTrainViewCell *)[[[NSBundle  mainBundle]  loadNibNamed:@"GMTrainViewCell" owner:self options:nil]  lastObject];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    XZTrainRecord * model = self.dataSource[indexPath.row];
    cell.model = model;
    return cell;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 95;
}

#pragma mark - Setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    return _dataSource;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kBottomSafeHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator =false;
        _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        //注册
        [_tableView registerNib:[UINib nibWithNibName:@"GMTrainViewCell" bundle:nil] forCellReuseIdentifier:@"GMTrainViewCell"];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullNewsData)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addMoreNewsData)];
        _tableView.mj_footer.hidden =YES;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
#pragma mark - Networking
- (void)pullNewsData{
    self.pageIndex = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    
    __weak typeof(self)weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=GetMyTrainList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
        
                NSArray *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZTrainRecord mj_objectArrayWithKeyValuesArray:dataInfo];
                
                [weakSelf.dataSource removeAllObjects];
                [weakSelf.dataSource addObjectsFromArray:newsArray];
                [weakSelf.tableView.mj_footer endRefreshing];
                [weakSelf.tableView.mj_header endRefreshing];
                if (weakSelf.dataSource.count == 0) {
                    [weakSelf.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakSelf.tableView reloadData];
            }else{
                
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakSelf.view];
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakSelf.view];
        }
    }];
}
- (void)addMoreNewsData{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    __weak typeof(self)weakSelf = self;
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=GetMyTrainList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZTrainRecord mj_objectArrayWithKeyValuesArray:dataInfo];
                [weakSelf.dataSource addObjectsFromArray:newsArray];
                if (dataInfo.count>0) {
                    [weakSelf.tableView.mj_footer endRefreshing];
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakSelf.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                }
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
                [weakSelf.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakSelf.view];
            }
        }else{
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakSelf.view];
        }
    }];
}
@end
